<template>
  <div :style="conheight">
    <split-pane split="vertical"
                :min-percent="8"
                :default-percent="20">
      <template slot="paneL">
        <el-scrollbar :style="conheight">
          <el-card shadow="never"
                   class="my-contain-card">
            <el-tree draggable
                     :allow-drop="cfgJobTreeAllowDrop"
                     :allow-drag="cfgJobTreeAllowDrag"
                     ref="cfgJobTree"
                     :highlight-current="true"
                     @node-drop="sort"
                     empty-text="暂无数据"
                     :data="cfgJobList"
                     :props="defaultProps"
                     :expand-on-click-node="false"
                     node-key="id"
                     @node-expand="handleTreeExpand"
                     @node-collapse="handleTreeCollapse"
                     @current-change="handleTreeCurrentChange">
              <span class="custom-tree-node"
                    slot-scope="{node,data}">
                <!-- this.setCfgJobFieldValue(data, 'editCrontab', false);
            this.setCfgJobFieldValue(data, 'editDependence', false); -->
                <span>
                  <i :class="data.iconClass"></i>
                  <i v-if="data.id == null"
                     class="el-icon-star-off"></i>
                  <i v-if="data.izEnabled == '0'"
                     class="el-icon-circle-close"></i>
                  <i v-if="data.edit"
                     class="el-icon-edit"></i>
                  <i v-if="data.editCrontab || data.editDependence"
                     class="el-icon-edit-outline"></i>
                  {{ data.jobName }}</span>
              </span>
            </el-tree>
          </el-card>
        </el-scrollbar>
      </template>
      <template slot="paneR">
        <!-- style="height:580px" -->
        <el-scrollbar :style="conheight">
          <el-card shadow="never"
                   class="my-contain-card">
            <el-drawer :visible.sync="hostDrawer.show"
                       :with-header="false"
                       direction="rtl">
              <el-card shadow="never">
                <div slot="header"
                     class="clearfix">
                  <el-row>
                    <el-col :span="16">
                      <el-tag type="info">请选择运行此作业的主机</el-tag>
                    </el-col>
                    <el-col :span="8">
                      <el-button circle
                                 size="mini"
                                 @click="handleHostOk()">确定</el-button>
                      <el-button circle
                                 size="mini"
                                 @click="hostDrawer.show = false">取消</el-button>
                    </el-col>
                  </el-row>
                </div>
                <el-table :data="hostDrawer.data"
                          ref="host_table"
                          highlight-current-row
                          @current-change="handleHostCurrentChange"
                          style="width: 100%,height:100%">
                  <el-table-column type="index"
                                   label="序号"
                                   width="50">
                  </el-table-column>
                  <el-table-column prop="name"
                                   align="left"
                                   label="主机名称">
                  </el-table-column>
                </el-table>
              </el-card>
            </el-drawer>

            <template v-if="currentJob == null">
              <!-- 欢迎使用！ 请选择右边的作业组或作业进行操作... -->
            </template>

            <template v-else-if="currentJob.jobType == '0' || currentJob.jobType == '2'">
              <!--- currentJobGrouTreeDialogVisible dialog begin-->
              <el-dialog :visible.sync="currentJobGrouTreeDialogVisible"
                         width="40%"
                         :show-close="false">
                <div slot="title">
                  <el-row>
                    <el-col :span="16">
                      <el-tag v-if="currentJobGrouTreeDialogAction == 'disable'">
                        作业组下线:
                      </el-tag>
                      <el-tag v-if="currentJobGrouTreeDialogAction == 'enable'">
                        作业组上线:
                      </el-tag>
                      <el-tag v-if="currentJobGrouTreeDialogAction == 'copy'">
                        作业组复制:
                      </el-tag>
                      <el-tag type="info">
                        {{currentJob.jobName}}
                      </el-tag>
                    </el-col>
                    <el-col :span="8">
                      <el-button size="small"
                                 circle
                                 type="warning"
                                 @click="currentJobGrouTreeDialogVisible = false">取消</el-button>
                      <el-popconfirm v-if="currentJobGrouTreeDialogAction == 'disable'"
                                     title="这将使作业组及下面所有作业下线，他们的执行计划也全都撤消，确定吗？"
                                     confirmButtonText='确定下线'
                                     cancelButtonText='点错了，不要下线'
                                     icon="el-icon-info"
                                     iconColor="red"
                                     @onConfirm="handleJobGroupDisableComfirm()">
                        <el-button v-if="currentJobGrouTreeDialogAction == 'disable'"
                                   size="small"
                                   slot="reference"
                                   type="primary"
                                   circle>下线</el-button>
                      </el-popconfirm>

                      <el-popconfirm v-if="currentJobGrouTreeDialogAction == 'enable'"
                                     title="这将使作业组及选中的作业上线，他们的执行计划还需要逐一启用，确定吗？"
                                     confirmButtonText='确定上线'
                                     cancelButtonText='点错了，不要上线'
                                     icon="el-icon-info"
                                     iconColor="red"
                                     @onConfirm="handleJobGroupEnableComfirm()">
                        <el-button v-if="currentJobGrouTreeDialogAction == 'enable'"
                                   size="small"
                                   slot="reference"
                                   type="primary"
                                   circle>上线</el-button>
                      </el-popconfirm>

                      <el-button v-if="currentJobGrouTreeDialogAction == 'copy'"
                                 size="small"
                                 type="primary"
                                 circle
                                 @click="handleJobGroupCopyComfirm()">复制</el-button>
                    </el-col>
                  </el-row>
                </div>
                <el-divider></el-divider>
                <div style="height:280px">
                  <el-scrollbar style="height:100%">
                    <el-tree ref="currentJobGroupTree"
                             :data="newJobGroup.children"
                             :props="defaultProps"
                             node-key="id"
                             height="300px"
                             show-checkbox
                             :expand-on-click-node="false">
                      <span class="custom-tree-node"
                            slot-scope="{node,data}">
                        <span>
                          <i :class="data.iconClass"></i>
                          <i v-if="data.izEnabled == '0'"
                             class="el-icon-circle-close"></i>
                          {{ data.jobName }}</span>
                      </span>
                    </el-tree>
                  </el-scrollbar>
                </div>
              </el-dialog>
              <!--- currentJobGrouTreeDialogVisible dialog end-->

              <!-- :title="currentJob.jobName" -->
              <el-dialog :visible.sync="jobGroupRunDialogVisible"
                         width="60%"
                         :show-close="
                         true">
                <div slot="title">
                  <el-row>
                    <el-col :span="12">
                      {{currentJob.jobName}}
                    </el-col>
                    <el-col :span="8">
                      <el-button size="small"
                                 circle
                                 @click="jobGroupRunDialogVisible = false">启动</el-button>
                      <el-button size="small"
                                 circle
                                 @click="jobGroupRunDialogVisible = false">停止</el-button>
                    </el-col>
                  </el-row>
                </div>
                <el-table :data="jobStatusList"
                          v-if="true"
                          border
                          height="380"
                          style="width: 100%">
                  <el-table-column label="序号"
                                   type="index"
                                   fixed
                                   width="50">
                  </el-table-column>
                  <el-table-column prop="jobName"
                                   fixed
                                   label="作业名称"
                                   min-width="180">
                  </el-table-column>
                  <el-table-column prop="status"
                                   label="状态"
                                   width="80">
                  </el-table-column>
                  <el-table-column label="发生时间"
                                   width="180">
                    <template slot-scope="{row}">
                      <span>{{ formatTime(row.statusTime)}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="作业组时间"
                                   width="180">
                    <template slot-scope="{row}">
                      <span>{{ formatTime(row.taskParentSchedulerTime)}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作"
                                   width="100">
                    <template slot-scope="{row}">
                      <span>执行记录</span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-dialog>

              <el-card shadow="never">
                <div slot="header">
                  <!--作业组-->
                  <el-row>
                    <el-col :span="16">
                      <template v-if="currentJob.edit == false">
                        <el-button circle
                                   size="small"
                                   type="success"
                                   plain
                                   @click="handleJobGroupCopy()">复制</el-button>
                        <!-- 下线了才能编辑, 防止编辑时有新的任务 -->
                        <el-button v-if="currentJob.izEnabled == '0'"
                                   circle
                                   size="small"
                                   type="success"
                                   plain
                                   @click="handleJobGroupEdit()">
                          编辑
                        </el-button>
                        <el-button circle
                                   size="small"
                                   type="success"
                                   plain
                                   @click="currentJob.showDetail = ! currentJob.showDetail">详情</el-button>
                        <el-button v-if="currentJob.izEnabled == '0'"
                                   circle
                                   type="success"
                                   plain
                                   size="small"
                                   @click="handleJobGroupEnable()">上线</el-button>
                        <el-button v-if="currentJob.izEnabled == '1'"
                                   circle
                                   type="success"
                                   plain
                                   size="small"
                                   @click="handleJobGroupDisable()">下线</el-button>
                      </template>
                      <template v-else>
                        <el-button circle
                                   size="small"
                                   plain
                                   type="warning">
                          取消
                        </el-button>
                        <el-button circle
                                   size="small"
                                   type="success"
                                   plain
                                   @click="handleJobGroupPost()">
                          提交
                        </el-button>
                      </template>

                    </el-col>
                    <el-col :span="8">
                      <el-tag>{{currentJob.jobName}}</el-tag>
                      <el-divider direction="vertical"></el-divider>
                      <el-tag>
                        {{getDictLabel('job_is_enabled', currentJob.izEnabled)}}
                      </el-tag>
                    </el-col>
                  </el-row>
                </div>
              </el-card>
              <el-card shadow="never"
                       v-show="currentJob.showDetail">
                <div slot="header">
                  作业组详细信息
                  <!-- <el-divider content-position="left">精益求益 至臻至善</el-divider> -->
                </div>
                <!-- <el-card shadow="never"
                           v-if="true"> -->
                <el-form :disabled="!currentJob.edit"
                         ref="form"
                         size="small"
                         :model="currentJob"
                         label-width="100px">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="作业组名">
                        <el-input v-model="currentJob.jobName"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-tag>
                        {{getDictLabel('job_is_enabled', currentJob.izEnabled)}}
                      </el-tag>

                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="JOB_ID">
                        <el-tag type="info">
                          {{currentJob.id}}
                        </el-tag>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <template v-if="currentJob.jobType == '2'">
                    <el-row :gutter="20">
                      <el-col :span="12">
                        <el-form-item label="最大运行时长">
                          <el-input v-model="currentJob.maxDuration"
                                    placeholder="可用于异常报警"
                                    oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="最大并发数">
                          <el-input v-model="currentJob.maxParallel"
                                    placeholder="组内同时运行最大并发作业数"
                                    oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </template>
                  <el-row>
                    <el-form-item label="备注信息">
                      <el-input type="textarea"
                                v-model="currentJob.remark"></el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item label="执行计划">
                      <!-- <template v-if="currentJob.hasCrontab == '1'"> -->
                      <a v-for="item in currentJob.monitorPlans"
                         :key="item.id">
                        <el-tag v-if="item.izEnabled == '0'"
                                type="info">{{item.name}}</el-tag>
                        <el-tag v-else>{{item.name}}</el-tag>
                        <el-divider direction="vertical"></el-divider>
                      </a>
                      <!-- </template> -->
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item label="启动依赖"
                                  placeholder="启动依赖">
                      <a v-for="item in currentJob.monitorDependencies"
                         :key="item.id">
                        <el-tag v-if="item.dependType =='0'">{{item.dependJobName}}:{{getDictLabel('depend_type', item.dependType)}}:{{item.dependValue}}</el-tag>
                        <el-tag v-else>{{item.dependJobName}}:{{getDictLabel('depend_type', item.dependType)}}:{{getDictLabel('task_status', item.dependValue)}}</el-tag>
                        <el-divider direction="vertical"></el-divider>
                      </a>
                    </el-form-item>
                  </el-row>
                </el-form>
                <!-- </el-card> remark -->
              </el-card>
              <el-table :data="currentJob.children"
                        v-if="true"
                        border
                        style="width: 100%">
                <el-table-column label="序号"
                                 type="index"
                                 fixed
                                 width="60">
                </el-table-column>
                <el-table-column prop="jobName"
                                 fixed
                                 label="作业名称"
                                 width="180">
                </el-table-column>
                <el-table-column prop="izEnabled"
                                 label="上线状态"
                                 align="center"
                                 width="100">
                  <template slot-scope="{row}">
                    <el-tag type="info"
                            v-if="row.izEnabled =='0'">未上线</el-tag>
                    <el-tag v-else>已上线</el-tag>
                  </template>
                </el-table-column>
                <el-table-column v-if="currentJob.jobType =='2'"
                                 label="运行模式"
                                 align="center"
                                 width="80">
                  <template slot-scope="{row}">
                    <el-tag type="success"
                            v-if="row.serialProcessing =='0'">并行</el-tag>
                    <el-tag type="warning"
                            v-else>串行</el-tag>
                  </template>
                </el-table-column>

                <el-table-column prop="jobName"
                                 label="执行计划"
                                 width="380">
                  <template slot-scope="{row}">
                    <a v-for="item in row.monitorPlans"
                       :key="item.id">
                      <el-tag v-if="item.izEnabled == '0'"
                              type="info">{{item.name}}</el-tag>
                      <el-tag v-else>{{item.name}}</el-tag>
                      <el-divider direction="vertical"></el-divider>
                    </a>
                  </template>

                </el-table-column>
                <el-table-column width="360"
                                 align="center"
                                 label="命令行">
                  <el-table-column prop="startCommand"
                                   label="启动"
                                   width="380">
                  </el-table-column>
                  <el-table-column prop="stopCommand"
                                   width="380"
                                   label="停止">
                  </el-table-column>
                </el-table-column>
                <el-table-column width="280"
                                 label="运行标识">
                  <template slot-scope="{row}">
                    <span v-if="row.jobType =='1'">{{row.psKeyWords}}</span>
                    <span v-else>N/A</span>
                  </template>
                </el-table-column>
                <el-table-column width="120"
                                 align="center"
                                 label="自动重启">
                  <el-table-column prop="daemonRestartTimes"
                                   width="60"
                                   align="center"
                                   label="次数">
                  </el-table-column>
                  <el-table-column prop="daemonRestartInterval"
                                   width="60"
                                   align="center"
                                   label="间隔">
                  </el-table-column>
                </el-table-column>
                <el-table-column prop="remark"
                                 width="280"
                                 label="备注信息">
                </el-table-column>
              </el-table>
              <!-- </el-card> -->

            </template>
            <!-- 作业 -->
            <template v-else>
              <el-card shadow="never">
                <div slot="header">
                  <!-- <el-button style="float: right; padding: 5px 15px"
                         type="text">更多 ></el-button> -->
                  <el-row>
                    <template v-if="currentJob.edit">
                      <!-- 在作业组编辑状态下, 进程才可以复制 -->
                      <el-button circle
                                 size="small"
                                 @click="handleJobCopy()">复制</el-button>
                      <el-popconfirm title="这将直接从系统删除本作业，确定吗？"
                                     confirmButtonText='狠心删除'
                                     cancelButtonText='点错了，不要删'
                                     icon="el-icon-info"
                                     iconColor="red"
                                     @onConfirm="handleDeleteJob()">
                        <el-button circle
                                   slot="reference"
                                   type="success"
                                   plain
                                   size="small">删除</el-button>
                      </el-popconfirm>
                    </template>
                    <template v-else>
                      <el-button circle
                                 v-if="currentJob.izEnabled == '0'"
                                 :disabled="!checkJobGroupIzEnable()"
                                 size="small"
                                 type="success"
                                 plain
                                 @click="handleJobEnable()">上线</el-button>
                      <el-button circle
                                 v-if="currentJob.izEnabled == '1'"
                                 size="small"
                                 type="success"
                                 plain
                                 @click="handleJobDisable()">下线</el-button>

                    </template>

                  </el-row>
                </div>
                <!-- <el-card shadow="never"
                           v-if="true"> -->
                <el-form ref="jobForm"
                         :disabled="!currentJob.edit"
                         size="small"
                         :model="currentJob"
                         label-width="100px">
                  <el-row :gutter="20">
                    <el-col :span="10">
                      <el-form-item label="作业名称">
                        <el-input v-model="currentJob.jobName"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="2">
                      <el-tag>
                        {{getDictLabel('job_is_enabled', currentJob.izEnabled)}}
                      </el-tag>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="运行主机">
                        <!-- <el-input v-model="currentJob.hostName"></el-input> -->
                        <el-input :readonly="true"
                                  v-model="currentJob.hostName">
                          <el-button slot="append"
                                     icon="el-icon-more"
                                     @click="showHostDrawer()"></el-button>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4">
                      <el-form-item label="JOB_ID">
                        <el-tag type="info">
                          {{currentJob.id}}
                        </el-tag>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <!-- v-if="currentJob.jobType == '1'" -->
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="启动命令">
                        <el-input v-model="currentJob.startCommand"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="停止命令">
                        <el-input v-model="currentJob.stopCommand"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row v-if="currentJob.jobType == '3'"
                          :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="日志文件">
                        <el-input v-model="currentJob.logFileName"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="运行模式"
                                    placeholder="">
                        <el-select v-model="currentJob.serialProcessing"
                                   style="width:100%;"
                                   align="center"
                                   size="small">
                          <el-option v-for="el_select_item 
                                      in getOptions('serial_processing')"
                                     :key="el_select_item.value"
                                     :label="el_select_item.label"
                                     :value="el_select_item.value" />
                        </el-select>
                        <!-- <el-input v-model="currentJob.serialProcessing"></el-input> -->
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="最大运行时长">
                        <el-input v-model="currentJob.maxDuration"
                                  oninput="value=value.replace(/[^\d]/g,'')"
                                  placeholder="可用于异常报警"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20"
                          v-if="currentJob.jobType == '1'">
                    <el-col :span="12">
                      <el-form-item label="日志文件">
                        <el-input v-model="currentJob.logFileName"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="重启次数"
                                    placeholder="">
                        <el-input v-model="currentJob.restartTimes"
                                  oninput="value=value.replace(/[^\d]/g,'')"
                                  placeholder="0 不需要自动重启"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="重启间隔">
                        <el-input placeholder="单位分钟"
                                  oninput="value=value.replace(/[^\d]/g,'')"
                                  v-model="currentJob.restartInterval"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row v-if="currentJob.jobType == '1'">
                    <el-form-item label="运行标识">
                      <el-input v-model="currentJob.psKeyWords"></el-input>
                    </el-form-item>
                  </el-row>
                  <el-form-item label="备注信息">
                    <el-input type="textarea"
                              v-model="currentJob.remark"></el-input>
                  </el-form-item>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="执行计划">
                        <!-- <template v-if="currentJob.hasCrontab == '1'"> -->
                        <a v-for="item in currentJob.monitorPlans"
                           :key="item.id">
                          <el-tag v-if="item.izEnabled == '0'"
                                  type="info">{{item.name}}</el-tag>
                          <el-tag v-else>{{item.name}}</el-tag>
                          <el-divider direction="vertical"></el-divider>
                        </a>
                        <!-- </template> -->
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="启动依赖"
                                    placeholder="启动依赖">
                        <a v-for="item in currentJob.monitorDependencies"
                           :key="item.id">
                          <el-tag v-if="item.dependType =='0'">{{item.dependJobName}}:{{getDictLabel('depend_type', item.dependType)}}:{{item.dependValue}}</el-tag>
                          <el-tag v-else>{{item.dependJobName}}:{{getDictLabel('depend_type', item.dependType)}}:{{getDictLabel('task_status', item.dependValue)}}</el-tag>
                          <el-divider direction="vertical"></el-divider>
                        </a>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>

              </el-card>
            </template>
          </el-card>
        </el-scrollbar>
      </template>
    </split-pane>
  </div>

</template>
<script>
import splitPane from "vue-splitpane";
import { formatDate } from "@/utils/date";
import { hasPermission, getEntries, getLabel } from "@/utils/dict";
import { apiHostList, apiJobList, apiJobCopy, apiJobDelete, apiJobResort, apiJobEnable, apiJobDisable, apiJobUpdate } from "@/api/monitor";

export default {
  name: "MonitorJob",
  data() {
    return {
      myBackToTopStyle: {
        right: '50px',
        bottom: '50px',
        width: '40px',
        height: '40px',
        'border-radius': '4px',
        'line-height': '45px', // 请保持与高度一致以垂直居中 Please keep consistent with height to center vertically
        background: '#e7eaf1'// 按钮的背景颜色 The background color of the button
      },
      hostDrawer: {
        show: false,
        data: [],
        hostName: ''
      },
      conheight: {
        height: ''
      },
      jobGroupTableHeight: '560px',
      jobTableHeight: '',

      defaultNewCrontab: {
        id: null,
        jobId: null,
        actionType: '0',
        schedulerType: '1',
        logFileName: null,
        actionTime: null,
        izEnabled: '0',
        minute: '*',
        hour: '*',
        day: '*',
        weekday: '*',
        month: '0',
        runDuration: 180,
        name: '默认值,修改我吧',
        remark: '备注, 详细说明调度计划',
      },

      currentJobGrouTreeDialogVisible: false,
      //action 可以是 copy, disable, enable
      currentJobGrouTreeDialogAction: "",

      multipleSelection: [],
      multipleDependenceSelection: [],

      jobGroupRunDialogVisible: false,


      jobDependencePickJobDialogVisible: false,
      jobTaskProcessDialogVisible: false,
      listLoading: false,
      currentJob: null,
      newJobGroup: { children: [] },
      // job_name, host_name, daemon_restart_times, daemon_restart_interval, command, ps_key_words, iz_canceled, remark
      cfgJobList: [],
      jobStatusList: [],
      defaultProps: {
        children: 'children',
        label: 'jobName',
      }
    };
  },

  created() {
    this.callCfgJobList();
    window.addEventListener('resize', this.getHeight);
    this.getHeight();
  },

  methods: {
    hasPermission(url) {
      return hasPermission(url)
    },

    getOptions(dictKey) {
      return getEntries(dictKey);
    },

    getDictLabel(dictKey, dictValue) {
      return getLabel(dictKey, dictValue);
    },

    formatTime(time) {
      if (time == null || time === '') {
        return 'N/A';
      }
      let date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    },

    showHostDrawer() {
      if (this.hostDrawer.data.length == 0) {
        apiHostList()
          .then(response => {
            this.listLoading = false;
            const data = response.data;
            if (data) {
              this.$set(this.hostDrawer, 'data', data);
              //this.hostDrawer.data = data;
            }
          });
      }

      this.hostDrawer.show = true;
    },

    handleHostOk() {
      this.currentJob.hostName = this.hostDrawer.hostName;
      this.hostDrawer.show = false;
    },

    handleHostCurrentChange(val) {
      this.hostDrawer.hostName = val.name;
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleDependenceSelectionChange(val) {
      this.multipleDependenceSelection = val;
    },


    getHeight() {
      //this.myHeight = window.innerHeight - 100;
      this.conheight.height = window.innerHeight - 100 + 'px';
      this.jobGroupTableHeight = window.innerHeight - 100 + 'px';
      this.jobTableHeight = window.innerHeight - 100 - 140 + 'px';
    },

    handleTreeCurrentChange(data, node) {
      this.currentJob = data;
    },

    cfgJobTreeAllowDrag(node) {
      if (node.data.jobType == '0' || node.data.jobType == '2') {
        return true;
      } else {
        return node.data.edit;
      }
    },

    cfgJobTreeAllowDrop(draggingNode, dropNode, type) {

      if ((dropNode.data.jobType == '0' || dropNode.data.jobType == '2')
        && (draggingNode.data.jobType == '0' || draggingNode.data.jobType == '2')) {
        return type === 'prev' || type === 'next';
      }

      //编辑状态下才能操作
      if (!dropNode.data.edit) {
        return false;
      }

      if (draggingNode.data.parentId === dropNode.data.parentId) {
        //同组拖拽作业是排序, 不需要提示
        return type === 'prev' || type === 'next';
      } else {
        // 不同组
        if (draggingNode.data.jobType == '0' || dropNode.data.jobType == '2') {
          //拖拽的是组, 不可以
          return false;
        } else if (dropNode.data.jobType == draggingNode.data.jobType) {
          //接收的是作业,
          return type === 'prev' || type === 'next';
        }

        return false;
      }
    },

    handleAddDependence() {
      this.jobDependencePickJobDialogVisible = true;
      this.$set(this.currentJob, 'editDependence', true);
      // this.currentJob.editDependence = true;
      this.$nextTick(function () {
        this.$refs.dependenceJobTree.setCheckedKeys([]);
      });
    },

    handleEditDependence() {
      this.$set(this.currentJob, 'editDependence', true);
    },




    handleAddDependenceConfirm() {
      this.jobDependencePickJobDialogVisible = false;
      //要为每个选中的作业添加上默认值 
      this.$refs.dependenceJobTree.getCheckedNodes().map((item) => {
        let newDependence = {};
        newDependence.id = null;
        newDependence.jobId = this.currentJob.id;
        newDependence.dependJobId = item.id;
        newDependence.dependJobName = item.jobName;
        if (item.jobType == '3') {
          //依赖作业是普通作业, 依赖默认为返回码等于0
          newDependence.dependType = '0';
          newDependence.dependValue = '0';
        } else {
          //依赖作业是守护进程作业, 作业组, 依赖默认为运行状态
          newDependence.dependType = '1';
          newDependence.dependValue = '2';
        }
        if (this.currentJob.monitorDependencies == null) {
          this.currentJob.monitorDependencies = []
        }
        this.currentJob.monitorDependencies.push(newDependence);
      });
      //开启编辑, 所有依赖都可编辑
      this.$set(this.currentJob, 'editDependence', true);
    },

    checkCrontabEdit() {
      if (this.currentJob.monitorPlans.length == 0) {
        return false;
      }

      let idx = this.currentJob.monitorPlans.length - 1;
      if (this.currentJob.monitorPlans[idx].id == null) {
        return true;
      }

      return false;
    },

    handleCreatNewCrontab() {
      let newCrontab = JSON.parse(JSON.stringify(this.defaultNewCrontab));
      newCrontab.jobId = this.currentJob.id;
      this.currentJob.monitorPlans.push(newCrontab);
    },


    sort(draggingNode, dropNode, type, event) {
      //TODO
      //组与组之间的顺序发生改变,  即时更新到数据库
      //这个操作是全局性的, 所以要求所有的组都要显示出来(已经删除的除外)
      if ((dropNode.data.jobType == '0' || dropNode.data.jobType == '2')
        && (draggingNode.data.jobType == '0' || draggingNode.data.jobType == '2')) {
        let myIds = []
        this.cfgJobList.map(e => {
          let myId = {}
          myId.id = e.id;
          myIds.push(myId);
        });

        this.listLoading = true;
        apiJobResort(myIds)
          .then(response => {
            this.listLoading = false;
            const data = response.data;
            if (data) {
              this.$message({
                type: 'success',
                message: data,
                duration: 3000
              });
              this.listLoading = false;
            }
          });
        this.listLoading = false;
      }
    },


    handleDeleteJob() {
      let currentJobGroupData = this.$refs.cfgJobTree.getNode(this.currentJob.parentId).data;
      let idx = currentJobGroupData.children.findIndex((item) => item.id === this.currentJob.id);
      let childrenLength = currentJobGroupData.children.length;
      if (childrenLength === 1) {
        var myIds = [];
        var myId = {};
        var myGroupId = {};
        myId.id = this.currentJob.id;
        myIds.push(myId);
        myGroupId.id = currentJobGroupData.id;
        myIds.push(myGroupId);

        this.$confirm('这是该组最后一个作业了! \r\n 继续操作将作业组也一并删除，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log("handleDeleteJob hhhh");

          apiJobDelete(myIds)
            .then(response => {
              this.$message({
                type: 'success',
                message: '删除成功!',
                duration: 3000
              });
            });
          let idxGroup = this.cfgJobList.findIndex((item) => item.id === currentJobGroupData.id);
          this.cfgJobList.splice(idxGroup, 1);
          currentJobGroupData.children.splice(idx, 1);
          this.listLoading = false;
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
            duration: 3000
          });
        });
      } else {
        let myIds = [];
        let myId = {};
        myId.id = this.currentJob.id;
        myIds.push(myId);
        this.listLoading = true;
        apiJobDelete(myIds)
          .then(response => {
            currentJobGroupData.children.splice(idx, 1);
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          });
        this.listLoading = false;

      }
      // let idxGroup = this.cfgJobList.findIndex((item) => item.id === currentJobGroupData.id);
      // console.log("idxGroup:" + idxGroup);
    },

    handleJobGroupCopy() {
      this.newJobGroup = JSON.parse(JSON.stringify(this.currentJob));
      this.currentJobGrouTreeDialogAction = "copy";
      this.currentJobGrouTreeDialogVisible = true;
      //TODO callApiJobGroupCopy()
    },

    checkJobGroupIzEnable() {
      if (this.currentJob.jobType == '0' || this.currentJob.jobType == '2') {
        return false;
      }

      let idx = this.cfgJobList.findIndex((item) => item.id === this.currentJob.parentId);
      if (this.cfgJobList[idx].izEnabled == "1") {
        return true;
      };

      return false;
    },


    handleJobCopy() {
      let currentJobGroupData = this.$refs.cfgJobTree.getNode(this.currentJob.parentId).data;

      let newJob = JSON.parse(JSON.stringify(this.currentJob));
      newJob.id = null;
      newJob.jobName = newJob.jobName + "_copy";
      currentJobGroupData.children.push(newJob);
    },

    handleTreeExpand(data, node, self) {
      data.iconClass = "el-icon-folder-opened";
    },

    handleTreeCollapse(data) {
      if (data.jobType == '0') {
        data.iconClass = "el-icon-folder-checked";
      } else {
        data.iconClass = "el-icon-folder";
      }
    },

    cancelEdit(row) {
      row.edit = false;
    },

    handleJobGroupEdit() {
      this.$set(this.currentJob, 'edit', true);
      this.$set(this.currentJob, 'showDetail', true);
      this.currentJob.children.map(e => {
        this.$set(e, 'edit', true);
      });
    },

    //TODO.
    //删除组, 组的顺序调整即时提交
    //编辑后的内容, 按整个工作组提交
    handleJobGroupPost() {
      this.currentJob.edit = false;
      this.currentJob.children.map(e => {
        this.$set(e, 'edit', false);
      });

      this.listLoading = true;
      apiJobUpdate(this.currentJob)
        .then(response => {
          //this.callCfgJobList();
          const data = response.data;
          if (data) {
            this.setCfgJobFieldValue(data, 'edit', false);
            this.setCfgJobFieldValue(data, 'editCrontab', false);
            this.setCfgJobFieldValue(data, 'editDependence', false);
            this.setCfgJobFieldValue(data, 'showDetail', false);
            let idx = this.cfgJobList.findIndex((item) => item.id === this.currentJob.id);
            this.cfgJobList.splice(idx, 1, data);
          }
          this.listLoading = false;
        });
      this.listLoading = false;


    },

    //作业上线
    handleJobEnable() {
      //作业组上线，需要先选择同时上线的作业
      //子作业的执行计划要再去执行计划里操作使其生效, 从而生成任务.
      let jobIds = [];
      // 作业
      let myId = {};
      myId.id = this.currentJob.id;
      jobIds.push(myId);

      apiJobEnable(jobIds)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            this.$set(this.currentJob, 'izEnabled', '1');
            if (this.currentJob.monitorPlans != null && this.currentJob.monitorPlans.length > 0) {
              this.$message({
                type: 'success',
                message: '作业上线成功！作业的执行计划还需要你逐一开启哦...',
                duration: 3000
              });
            } else {
              this.$message({
                type: 'success',
                message: '作业上线成功！',
                duration: 3000
              });
            }
            this.currentJobGrouTreeDialogVisible = false;
          }
        });
      this.listLoading = false;
    },


    //作业下线, 作业的执行计划也全被撤消
    handleJobDisable() {
      let jobIds = [];
      // 作业
      let myId = {};
      myId.id = this.currentJob.id;
      jobIds.push(myId);

      apiJobDisable(jobIds)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            this.$set(this.currentJob, 'izEnabled', '0');
            if (this.currentJob.monitorPlans != null && this.currentJob.monitorPlans.length > 0) {
              this.currentJob.monitorPlans.map(cc => {
                this.$set(cc, 'izEnabled', '0');
              });
              this.$message({
                type: 'success',
                message: '作业下线成功！作业的执行计划也都撤消成功了！',
                duration: 3000
              });
            } else {
              this.$message({
                type: 'success',
                message: '作业下线成功！',
                duration: 3000
              });
            }
            this.currentJobGrouTreeDialogVisible = false;
          }
        });
      this.listLoading = false;
    },

    //作业组下线，显示弹窗，确认下线
    handleJobGroupDisable() {
      this.currentJobGrouTreeDialogAction = "disable";
      this.currentJobGrouTreeDialogVisible = true;

      this.$nextTick(function () {
        this.newJobGroup = JSON.parse(JSON.stringify(this.currentJob));
        this.setCfgJobFieldValue(this.newJobGroup, 'disabled', true);
        let allKeys = [];
        this.newJobGroup.children.map(e => {
          allKeys.push(e.id);
        });
        this.$refs.currentJobGroupTree.setCheckedKeys(allKeys);
      })
    },

    //作业组上线, 显示弹窗, 选择作业
    handleJobGroupEnable() {
      this.currentJobGrouTreeDialogAction = "enable";
      this.currentJobGrouTreeDialogVisible = true;
      this.$nextTick(function () {
        this.newJobGroup = JSON.parse(JSON.stringify(this.currentJob));
        this.setCfgJobFieldValue(this.newJobGroup, 'enable', false);
        let allKeys = [];
        this.newJobGroup.children.map(e => {
          allKeys.push(e.id);
        });
        console.log(allKeys);
        this.$refs.currentJobGroupTree.setCheckedKeys(allKeys);
      })
    },

    //作业组下线确认, 真正提交数据库操作
    handleJobGroupDisableComfirm() {
      let jobIds = [];
      // 作业组
      let myId = {};
      myId.id = this.currentJob.id;
      jobIds.push(myId);

      // 作业组下的作业
      let selectedIds = this.$refs.currentJobGroupTree.getCheckedNodes().map(
        function (item, index, ary) { return item.id; });

      selectedIds.map(e => {
        let myId = {};
        myId.id = e;
        jobIds.push(myId);
      });

      this.listLoading = true;
      apiJobDisable(jobIds)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            //作业组的执行计划要撤消
            this.currentJob.izEnabled = "0";
            if (this.currentJob.monitorPlans != null && this.currentJob.monitorPlans.length > 0) {
              this.currentJob.monitorPlans.map(cc => {
                cc.izEnabled = "0";
              });
            }
            //作业组下面的作业执行计划也统统要撤消
            this.currentJob.children.map(e => {
              e.izEnabled = "0";
              if (e.monitorPlans != null && e.monitorPlans.length > 0) {
                e.monitorPlans.map(ec => {
                  ec.izEnabled = "0";
                });
              }
            });
            this.$message({
              type: 'success',
              message: '作业组下线成功！作业组和它下面的作业执行计划也全都撤消了！',
              duration: 3000
            });

            this.currentJobGrouTreeDialogVisible = false;
          }
        });
      this.listLoading = false;
    },

    //作业组上线，真正提交数据库操作.
    handleJobGroupEnableComfirm() {
      //作业组上线，需要先选择同时上线的作业
      //子作业的执行计划要再去执行计划里操作使其生效, 从而生成任务.
      let jobIds = [];
      // 作业组
      let myId = {};
      myId.id = this.currentJob.id;
      jobIds.push(myId);

      // 作业组下的作业
      let selectedIds = this.$refs.currentJobGroupTree.getCheckedNodes().map(
        function (item, index, ary) { return item.id; });

      selectedIds.map(e => {
        let myId = {};
        myId.id = e;
        jobIds.push(myId);
      });

      apiJobEnable(jobIds)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            this.currentJob.izEnabled = "1";
            this.callCfgJobList();
            this.$message({
              type: 'success',
              message: '作业组上线成功！作业组和它下面的作业执行计划还需要你逐一开启哦...',
              duration: 3000
            });
            this.currentJobGrouTreeDialogVisible = false;
          }
        });
      this.listLoading = false;
    },



    handleJobGroupCopyComfirm() {
      console.log(this.$refs.currentJobGroupTree.getCheckedNodes());
      if (this.$refs.currentJobGroupTree.getCheckedNodes().length == 0) {
        this.$message({
          type: 'info',
          message: '至少要选一个子作业噢...',
          duration: 3000
        });
        return;
      }

      let selectedIds = this.$refs.currentJobGroupTree.getCheckedNodes().map(
        function (item, index, ary) { return item.id; });

      let childrenIds = this.newJobGroup.children.map(
        function (item, index, ary) { return item.id; });

      let deletIds = []
      for (let j = 0, len = childrenIds.length; j < len; j++) {
        if (selectedIds.findIndex((item) => item === childrenIds[j]) === -1) {
          deletIds.push(childrenIds[j]);
        }
      }
      console.log("this id is not selected:" + deletIds);

      for (let h = 0, len = deletIds.length; h < len; h++) {
        let idx = this.newJobGroup.children.findIndex((item) => item.id === deletIds[h]);
        this.newJobGroup.children.splice(idx, 1);
      }
      console.log("this.newJobGroup.children:", this.newJobGroup.children);

      this.newJobGroup.edit = null;
      this.newJobGroup.iconClass = null;
      this.newJobGroup.jobName = this.newJobGroup.jobName + "_copy";
      this.listLoading = true;
      apiJobCopy(this.newJobGroup)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            var v = data;
            this.setCfgJobIconClass(v);
            this.setCfgJobFieldValue(v, 'edit', false);
            this.setCfgJobFieldValue(v, 'showDetail', false);
            this.setCfgJobFieldValue(v, 'taskProcesses', []);
            this.cfgJobList.push(v);
            this.currentJobGrouTreeDialogVisible = false;
          }
        });
      this.listLoading = false;
    },


    setCfgJobIconClass(v) {
      if (v.jobType == '0') {
        this.$set(v, 'iconClass', 'el-icon-folder-checked');
      } else if (v.jobType == '1') {
        this.$set(v, 'iconClass', 'el-icon-document-checked');
      } else if (v.jobType == '2') {
        this.$set(v, 'iconClass', 'el-icon-folder');
      } else if (v.jobType == '3') {
        this.$set(v, 'iconClass', 'el-icon-document');
      }
      else {
        //不应该有没有进程组的作业
        this.$set(v, 'iconClass', 'el-icon-s-release');
      }

      if (v.children != null && v.children.length != 0) {
        v.children.map(e => { this.setCfgJobIconClass(e) })
      }
    },

    setCfgJobFieldValue(v, fieldName, fieldValue) {
      this.$set(v, fieldName, fieldValue);

      if (v.children != null && v.children.length != 0) {
        v.children.map(e => { this.setCfgJobFieldValue(e, fieldName, fieldValue) })
      }
    },


    callApiCfgJobCopy(cfgJob) {
      this.listLoading = false;
    },

    messageSuccess() {
      this.$message({
        type: 'success',
        message: '提交成功!',
        duration: 3000
      });
    },

    callCfgJobList() {
      this.listLoading = true;
      apiJobList()
        .then(response => {
          this.$set(this, 'cfgJobList', []);
          this.$set(this, 'currentJob', null);
          this.listLoading = false;
          const data = response.data;
          console.log(data);
          if (data) {
            // https://vuejs.org/v2/guide/reactivity.html
            this.cfgJobList = data;
            this.cfgJobList.map(v => {
              this.setCfgJobIconClass(v);
              this.setCfgJobFieldValue(v, 'edit', false);
              this.setCfgJobFieldValue(v, 'showDetail', false);
              this.setCfgJobFieldValue(v, 'taskProcesses', []);
            });
            this.listLoading = false;
          }
        });
      this.listLoading = false;
    }
  }
}
</script>

<style>
.el-dialog__body {
  padding: 5px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}

.el-scrollbar .el-scrollbar__wrap {
  overflow-x: hidden;
}
.el-tree > .el-tree-node {
  min-width: 100%;
  display: inline-block;
}

.c-Button {
  border: none;
  border-radius: 2px;
}

.c-Button--close {
  background-color: red;
}
</style>

<style scoped>
.el-divider--horizontal {
  display: block;
  height: 1px;
  width: 100%;
  margin: 5px 0;
}

.my-contain-card {
  padding: 2px;
  width: 100%;
  /* height: 560px; */
  vertical-align: middle;
}

.left-container {
  background-color: #f38181;
  height: 100%;
}

.right-container {
  background-color: #fce38a;
  /* height: 200px; */
}
</style>

<style module>
.button {
  border: none;
  border-radius: 2px;
}

.buttonClose {
  background-color: red;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
